package org.ku.hero.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.ku.hero.api.protocol.Command;
import org.ku.hero.api.protocol.Packet;
import org.ku.hero.util.PacketUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 客户端发送心跳消息,服务端收到心跳消息后,返回心跳应答消息
 *
 *
 */
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter{
    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatReqHandler.class);
    private volatile ScheduledFuture<?> heartBeat;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final Packet packet = (Packet)msg;
        if (Command.toCmd(packet.getCmd()) == Command.HEART_BEAT){
            LOGGER.debug("客户端接收到了服务端心跳信息...");
            return;
        }else if (Command.toCmd(packet.getCmd()) == Command.VEHICLE_LOGIN){
            //登录成功
            LOGGER.debug("登录成功...");

            //每5秒发送一条心跳消息
            heartBeat = ctx.executor().scheduleAtFixedRate(() -> {
                Packet hb = PacketUtil.heartBeatPackge(packet.getVin());
                LOGGER.debug("客户端发送心跳信息给服务端...");
                ctx.writeAndFlush(hb);
            },0,5000, TimeUnit.MILLISECONDS);
        }
        //转发给下一个handler
        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (heartBeat != null){
            heartBeat.cancel(true);
            heartBeat = null;
        }
        ctx.fireExceptionCaught(cause);
    }
}
